<template>
  <div class="search-container">
    <!-- 白色卡片容器 -->
    <el-card class="search-card">
      <!-- 标题部分 -->
      <div class="search-header">
        <h2>菌物药种质资源库-检索</h2>
      </div>

      <!-- 检索表单部分 -->
      <el-form :model="form" label-width="100px" class="search-form">
        <el-form-item label="保藏编号">
          <el-input
              v-model="form.strain_number"
              placeholder="请输入保藏编号（可选填）"
              class="half-width-input"
          ></el-input>
        </el-form-item>

        <el-form-item label="属名">
          <el-select
              v-model="form.genus_name"
              filterable
              clearable
              placeholder="请选择或输入属名（可选填）"
              class="half-width-input"
              :style="form.genus_name ? { fontStyle: 'italic' } : {}"
          >
            <el-option
                v-for="item in genusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :style="{ fontStyle: 'italic' }"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="种名">
          <el-select
              v-model="form.species_name"
              filterable
              clearable
              placeholder="请选择或输入种名（可选填）"
              class="half-width-input"
              :style="form.species_name ? { fontStyle: 'italic' } : {}"
          >
            <el-option
                v-for="item in speciesOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :style="{ fontStyle: 'italic' }"
            />
          </el-select>
        </el-form-item>

        <!--        <el-form-item label="中文名称">-->
        <!--          <el-input-->
        <!--              v-model="form.chinese_name"-->
        <!--              placeholder="请输入中文名称（可选填）"-->
        <!--              class="half-width-input"-->
        <!--          ></el-input>-->
        <!--        </el-form-item>-->

        <el-form-item label="俗名">
          <el-input
              v-model="form.alias"
              placeholder="请输入俗名（可选填）"
              class="half-width-input"
          ></el-input>
        </el-form-item>

        <el-form-item label="药材名">
          <el-input
              v-model="form.medicinal_material_name"
              placeholder="请输入药材名（可选填）"
              class="half-width-input"
          ></el-input>
        </el-form-item>

        <el-form-item label="主要用途">
          <el-input
              v-model="form.main_function"
              placeholder="请输入主要用途（可选填）"
          ></el-input>
        </el-form-item>

        <el-form-item class="search-button">
          <el-button plain @click="handleReset">重置</el-button>
          <el-button plain @click="handleSearch">检索</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格部分 -->
      <el-table
          :data="paginatedData"
          border
          style="width: 100%; margin-top: 20px"
          class="strain-table"
          @selection-change="handleSelectionChange"
          ref="tableRef"
      >
        <el-table-column type="selection" width="55" />
        <!-- 菌株编号设置为可点击 -->
        <el-table-column prop="strain_number" label="菌株编号" width="220" align="center">
          <template #default="{ row }">
            <el-link type="primary" @click="handleStrainClick(row)">
              {{ row.strain_number }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="medicinal_material_name" label="药材名称" width="250" align="center"/>
        <el-table-column prop="strain_name" label="菌株拉丁名" width="250" align="center">
          <template #default="{ row }">
            <span style="font-style: italic;">{{ row.strain_name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="genus_name" label="属名" width="250" align="center">
          <template #default="{ row }">
            <span style="font-style: italic;">{{ row.genus_name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="species_name" label="种名" align="center">
          <template #default="{ row }">
            <span style="font-style: italic;">{{ row.species_name }}</span>
          </template>
        </el-table-column>
<!--        <el-table-column prop="source" label="来源" width="180" align="center" show-overflow-tooltip/>-->
<!--        <el-table-column prop="alias" label="别名" width="150" align="center" show-overflow-tooltip/>-->
<!--        <el-table-column prop="resource_distribution" label="资源分布" width="200" align="center" show-overflow-tooltip/>-->
<!--        <el-table-column prop="growth_environment" label="生长环境" width="200" align="center" show-overflow-tooltip/>-->
<!--        <el-table-column prop="resource_situation" label="资源情况" width="100" align="center"/>-->
<!--        <el-table-column prop="reference_sequence" label="参考ITS序列GenBank收录号" width="220" align="center" show-overflow-tooltip/>-->
<!--        <el-table-column prop="collection_and_processing" label="采收加工" width="150" align="center" show-overflow-tooltip/>-->
<!--        <el-table-column prop="chemical_composition" label="化学成分" width="200" align="center" show-overflow-tooltip/>-->
<!--        <el-table-column prop="main_function" label="功能主治" width="200" align="center" show-overflow-tooltip/>-->
<!--        <el-table-column prop="toxicity" label="毒性" width="120" align="center"/>-->
      </el-table>

      <div class="selection-actions">
        <el-button
            plain
            @click="clearSelection"
            :disabled="selectedRows.length === 0"
        >
          取消选择
        </el-button>

        <el-button
            plain
            @click="handleDownload"
            :disabled="tableData.length === 0"
            style="float: right;"
        >
          下载
        </el-button>
      </div>

      <!-- 分页组件 -->
      <el-pagination
          class="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>

    <el-dialog
        v-model="resultDialogVisible"
        :title="resultDialogTitle"
        width="30%"
    >
      <span>{{ resultDialogMessage }}</span>
      <template #footer>
        <el-button @click="resultDialogVisible = false">OK</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { SearchFunForm } from '~/types/search'
import { useRoute, useRouter } from 'vue-router';
import { searchMedicTask } from "~/api/searchApi";
import { useSpeciesStore } from '~/stores/soeciesStore'
import * as XLSX from 'xlsx';

const route = useRoute();
const router = useRouter();
const speciesStore = useSpeciesStore()

// 搜索表单数据
const form = reactive<SearchFunForm>({
  page: 1,
  page_size: 10,
  strain_number: null,
  genus_name: null,
  species_name: null,
  chinese_name: null,
  alias: null,
  medicinal_material_name: null,
  main_function: null
});

// 从store获取数据
const genusOptions = computed(() => speciesStore.genusOptions)
const speciesOptions = ref<Array<{ value: string; label: string }>>([])

// 根据属名筛选种名
const filterSpeciesByGenus = (genus: string | null) => {
  if (!genus) {
    speciesOptions.value = speciesStore.getAllSpeciesOptions()
    return
  }

  const speciesList = speciesStore.speciesData[genus] || []
  speciesOptions.value = speciesList.map(species => ({
    value: species,
    label: species
  }))
}

// 根据种名筛选属名
const filterGenusBySpecies = (species: string | null) => {
  if (!species) {
    return
  }

  const map = speciesStore.getSpeciesToGenusMap()
  const genus = map[species]
  if (genus && form.genus_name !== genus) {
    form.genus_name = genus
  }
}

// 观察属名变化
watch(() => form.genus_name, (newVal) => {
  if (newVal && form.species_name) {
    const map = speciesStore.getSpeciesToGenusMap()
    const currentSpeciesGenus = map[form.species_name]
    if (currentSpeciesGenus !== newVal) {
      form.species_name = null
    }
  }
  filterSpeciesByGenus(newVal)
})

// 观察种名变化
watch(() => form.species_name, (newVal) => {
  filterGenusBySpecies(newVal)
})

const resultDialogVisible = ref(false)
const resultDialogTitle = ref('')
const resultDialogMessage = ref('')

// 表格数据
interface SearchResult {
  strain_number: string | null;
  medicinal_material_name: string | null;
  strain_name: string | null;
  genus_name: string | null;
  species_name: string | null;
  source: string | null;
  alias: string | null;
  resource_distribution: string | null;
  growth_environment: string | null;
  resource_situation: string | null;
  reference_sequence: string | null;
  collection_and_processing: string | null;
  chemical_composition: string | null;
  main_function: string | null;
  toxicity: string | null;
  fungal_medicine_image: string | null;
  fruiting_body_image: string | null;
  mycelium_image: string | null;
  microscopic_features_image: string | null;
}

const tableData = ref<SearchResult[]>([]);
const loading = ref(false);

// 分页相关数据
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 计算当前页显示的数据
const paginatedData = computed(() => {
  return tableData.value;
});

// 清除空值参数
const cleanParams = (params: any) => {
  const cleaned: any = {};
  for (const key in params) {
    if (params[key] !== null && params[key] !== '') {
      cleaned[key] = params[key];
    }
  }
  return cleaned;
};

// 重置表单
const handleReset = () => {
  form.page = 1;
  form.page_size = 10;
  form.strain_number = null;
  form.genus_name = null;
  form.species_name = null;
  form.chinese_name = null;
  form.alias = null;
  form.medicinal_material_name = null;
  form.main_function = null;

  // 重置表格数据
  tableData.value = [];
  currentPage.value = 1;
  pageSize.value = 10;
  total.value = 0;
};

// 处理菌株编号点击
const handleStrainClick = (row: SearchResult) => {
  // 将搜索表单数据和当前行数据传递到详情页
  router.push({
    path: '/search/FungiDetail',
    query: {
      strainData: JSON.stringify(row),
      searchForm: JSON.stringify(form)
    }
  });
};

// 搜索方法
const handleSearch = async (isPageChange: boolean = false) => {
  if (typeof isPageChange !== 'boolean') {
    isPageChange = false;
  }

  try {
    loading.value = true;
    tableData.value = []; // 清空旧数据

    // 准备请求参数
    const params = {
      page: currentPage.value,
      page_size: pageSize.value,
      strain_number: form.strain_number,
      genus_name: form.genus_name,
      species_name: form.species_name,
      chinese_name: form.chinese_name,
      alias: form.alias,
      medicinal_material_name: form.medicinal_material_name,
      main_function: form.main_function
    };

    // 清除空值参数
    const cleanedParams = cleanParams(params);

    // 调用API
    const response = await searchMedicTask(cleanedParams);

    if (response.success) {
      if (response.data && Array.isArray(response.data.list) && response.data.list.length > 0) {
        tableData.value = response.data.list.map(item => ({
          strain_number: item.strain_number || null,
          medicinal_material_name: item.medicinal_material_name || null,
          strain_name: item.strain_name || null,
          genus_name: item.genus_name || null,
          species_name: item.species_name || null,
          source: item.source || null,
          alias: item.alias || null,
          resource_distribution: item.resource_distribution || null,
          growth_environment: item.growth_environment || null,
          resource_situation: item.resource_situation || null,
          reference_sequence: item.reference_sequence || null,
          collection_and_processing: item.collection_and_processing || null,
          chemical_composition: item.chemical_composition || null,
          main_function: item.main_function || null,
          toxicity: item.toxicity || null,
          fungal_medicine_image: item.fungal_medicine_image || null,
          fruiting_body_image: item.fruiting_body_image || null,
          mycelium_image: item.mycelium_image || null,
          microscopic_features_image: item.microscopic_features_image || null
        }));

        // 只在不是页码变化时显示成功弹窗
        if (!isPageChange) {
          showResultDialog(true, '检索成功！');
        }
        total.value = response.data.total || 0;
      } else {
        showResultDialog(false, '无返回数据 ｜ 返回数据格式错误');
        tableData.value = [];
        total.value = 0;
      }
    } else {
      showResultDialog(false, response.error || '返回数据格式错误或没有数据');
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('搜索出错:', error);
    showResultDialog(false, '搜索失败');
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 分页变化处理方法
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  form.page_size = val;
  currentPage.value = 1;
  handleSearch(true);
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  form.page = val;
  handleSearch(true);
};

const showResultDialog = (isSuccess: boolean, message: string) => {
  resultDialogTitle.value = isSuccess ? 'Success' : 'Error'
  resultDialogMessage.value = message
  resultDialogVisible.value = true
}

// 添加表格引用和选中行数据
const tableRef = ref();
const selectedRows = ref<SearchResult[]>([]);

// 处理选择变化
const handleSelectionChange = (rows: SearchResult[]) => {
  selectedRows.value = rows;
};

// 清除选择
const clearSelection = () => {
  tableRef.value?.clearSelection();
  selectedRows.value = [];
};

// 下载方法
const handleDownload = () => {
  const dataToDownload = selectedRows.value.length > 0
      ? selectedRows.value
      : tableData.value;

  if (dataToDownload.length === 0) {
    showResultDialog(false, '没有数据可下载');
    return;
  }

  try {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const dateString = `${year}${month}${day}`;

    const ws = XLSX.utils.json_to_sheet(dataToDownload);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "菌物药数据");
    XLSX.writeFile(wb, `菌物药种质资源数据_${dateString}.xlsx`);
    showResultDialog(true, selectedRows.value.length > 0
        ? '选中数据下载成功！'
        : '全部数据下载成功！');
  } catch (error) {
    console.error('下载失败:', error);
    showResultDialog(false, '下载失败');
  }
};

// 在组件挂载时检查路由参数
onMounted(async () => {
  await speciesStore.fetchSpeciesRelation('Medicinal')
  speciesOptions.value = speciesStore.getAllSpeciesOptions()

  // 检查是否有从详情页返回的搜索表单数据
  if (route.query.returnSearchForm) {
    try {
      const savedForm = JSON.parse(route.query.returnSearchForm as string);
      Object.assign(form, savedForm);

      // 恢复分页状态
      if (savedForm.page) currentPage.value = savedForm.page;
      if (savedForm.page_size) pageSize.value = savedForm.page_size;

      // 执行搜索
      handleSearch(true);
    } catch (error) {
      console.error('恢复搜索表单失败:', error);
    }
  } else if (route.query.searchType && route.query.searchKeyword) {
    // 原有的路由参数处理逻辑
    const searchType = route.query.searchType as string;
    const searchKeyword = route.query.searchKeyword as string;

    handleReset();

    if (searchKeyword !== '') {
      switch (searchType) {
        case 'strain_number':
          form.strain_number = searchKeyword;
          break;
        case 'genus_name':
          form.genus_name = searchKeyword;
          break;
        case 'species_name':
          form.species_name = searchKeyword;
          break;
        case 'chinese_name':
          form.chinese_name = searchKeyword;
          break;
        case 'alias':
          form.alias = searchKeyword;
          break;
        case 'medicinal_material_name':
          form.medicinal_material_name = searchKeyword;
          break;
        case 'main_function':
          form.main_function = searchKeyword;
          break;
      }
    }

    currentPage.value = 1
    pageSize.value = 10
    handleSearch();
  }
});
</script>

<style scoped>
.search-container {
  margin: 0 20px 20px 20px;
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  border-radius: 8px;
}

.search-card {
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.search-header h2 {
  color: #303133;
  font-size: 24px;
  margin-bottom: 10px;
}

.search-form {
  margin-top: 20px;
}

.half-width-input {
  width: 50%;
}

.search-button {
  text-align: center;
  margin-top: 10px;
  position: relative;
}

.strain-table {
  margin-top: 30px;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}

:deep(.el-table th.el-table__cell) {
  background-color: #f5f7fa;
  color: #303133;
  font-weight: bold;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-pagination.is-background .btn-prev),
:deep(.el-pagination.is-background .btn-next),
:deep(.el-pagination.is-background .el-pager li) {
  background-color: #fff;
  border: 1px solid #dcdfe6;
}

:deep(.el-pagination.is-background .el-pager li:not(.disabled).active) {
  background-color: #409eff;
  color: #fff;
}

:deep(.el-pagination.is-background .el-pager li:not(.disabled):hover) {
  color: #409eff;
}

.selection-actions {
  margin-top: 20px;
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-start;
}

:deep(.el-table .el-checkbox__inner) {
  width: 16px;
  height: 16px;
}

:deep(.el-table .el-checkbox__inner::after) {
  height: 8px;
  left: 5px;
  width: 4px;
}
</style>